package com.itheima.service.imgl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.itheima.dto.DishDto;
import com.itheima.mapper.DishMapper;
import com.itheima.pojo.Dish;
import com.itheima.pojo.DishFlavor;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;


    @Override
    @Transactional//开启事务
    public void saveWithFlavor(DishDto dishDto) {
        //先保存菜品信息
        this.save(dishDto);

        //在保存菜品口味信息
        List<DishFlavor> flavors = dishDto.getFlavors();
        //从菜品id中给每个菜品口味赋值id
        flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishDto.getId()));
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public DishDto getByIdWithFlavor(Long id) {
        //查询菜品基本信息，从dish表中查询
        Dish dish = this.getById(id);

        //查询菜品信息对应的口味信息
        DishDto dishDto = new DishDto();
        QueryWrapper<DishFlavor> queryWrap = new QueryWrapper<>();
        queryWrap.eq("dish_id",dish.getId());
        List<DishFlavor> list = dishFlavorService.list(queryWrap);
        dishDto.setFlavors(list);

        //将菜品与口味信息拷贝并封装到Dto中
        BeanUtils.copyProperties(dish,dishDto);
        return dishDto;

    }

    @Override
    @Transactional//开启事务
    public void updateWithFlavor(DishDto dishDto) {
        //先更新菜品，并获取菜品id
        this.updateById(dishDto);

        //从菜品id中给菜品口味赋值id
        QueryWrapper<DishFlavor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dish_id", dishDto.getId());

        //先清空所有口味
        dishFlavorService.remove(queryWrapper);

        //再添加当前提交过来的口味数据---dish_flavor表的insert操作
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.forEach(flavor -> flavor.setDishId(dishDto.getId()));
        dishFlavorService.saveBatch(flavors);


    }
}
